import scala.actors.Actor
import scala.actors.Actor._
import scala.actors.OutputChannel
import java.net.URL

/**
 * Message to tell this actor to go get the page size for a URL.
 */
case class GetPageSize(query: String, url: String)

/**
 * Actor that listens for GetPageSize(query, url) messages and goes and finds the size of that
 * particular page.
 *
 * Sends GotPageSize(query,url,size) or FailedToGetPageSize(query,url) messages to the SummaryActor.
 */
class GetPageSizeActor(summaryActor: OutputChannel[Any]) extends Actor {

  def act() {
    loop {
      react {

        case GetPageSize(query, url) => {
          println("GetPageSizeActor received GetPageSize('" + query + "', '" + url + "')")
         
          try { 
          var urlfornet = new URL(url)
          var connection = urlfornet.openConnection()
          connection.connect()
          var stream = connection.getInputStream()

          var size = 0
          while (stream.read() != -1) {
            size = size + 1
          }
          stream.close()

          summaryActor ! GotPageSize(query, url, size)
          } catch {
            case e: Exception => summaryActor ! FailedToGetPageSize(query, url)
          }
        }

      }
    }
  }

}
